package cn.gson.springboot.model.service;

import java.math.BigDecimal;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.gson.springboot.model.dao.AdviceDAO;
import cn.gson.springboot.model.dao.AdviceDetailsDAO;
import cn.gson.springboot.model.dao.BedDAO;
import cn.gson.springboot.model.dao.CaseDAO;
import cn.gson.springboot.model.dao.CashDAO;
import cn.gson.springboot.model.dao.ClearingDAO;
import cn.gson.springboot.model.dao.ClearingDetailsDAO;
import cn.gson.springboot.model.dao.ComboDAO;
import cn.gson.springboot.model.dao.DepartmentsDAO;
import cn.gson.springboot.model.dao.ExamineDAO;
import cn.gson.springboot.model.dao.ExamineItemDAO;
import cn.gson.springboot.model.dao.ExamineRecordDAO;
import cn.gson.springboot.model.dao.ExchangeDAO;
import cn.gson.springboot.model.dao.HospitalDAO;
import cn.gson.springboot.model.dao.HospitalnoticeDAO;
import cn.gson.springboot.model.dao.InvoiceDAO;
import cn.gson.springboot.model.dao.InvoiceDetailsDAO;
import cn.gson.springboot.model.dao.LeaveDAO;
import cn.gson.springboot.model.dao.MedicalCardDAO;
import cn.gson.springboot.model.dao.OperationDAO;
import cn.gson.springboot.model.dao.OperationRecordDAO;
import cn.gson.springboot.model.dao.TheaterDAO;
import cn.gson.springboot.model.dao.UserDAO;
import cn.gson.springboot.model.mapper.AdviceMapper;
import cn.gson.springboot.model.mapper.BedMapper;
import cn.gson.springboot.model.mapper.CashMapper;
import cn.gson.springboot.model.mapper.ClearingMapper;
import cn.gson.springboot.model.mapper.DepartmentsMapper;
import cn.gson.springboot.model.mapper.DrugsYkMapper;
import cn.gson.springboot.model.mapper.ExamineMapper;
import cn.gson.springboot.model.mapper.HospitalMapper;
import cn.gson.springboot.model.mapper.MedicalMapper;
import cn.gson.springboot.model.mapper.OperationMapper;
import cn.gson.springboot.model.mapper.RepertoryMapper;
import cn.gson.springboot.model.mapper.UserMapper;
import cn.gson.springboot.model.pojos.Advice;
import cn.gson.springboot.model.pojos.AdviceDetail;
import cn.gson.springboot.model.pojos.Bed;
import cn.gson.springboot.model.pojos.Case;
import cn.gson.springboot.model.pojos.Cash;
import cn.gson.springboot.model.pojos.Clearing;
import cn.gson.springboot.model.pojos.ClearingDetail;
import cn.gson.springboot.model.pojos.Combo;
import cn.gson.springboot.model.pojos.DepartmentsPx;
import cn.gson.springboot.model.pojos.Examine;
import cn.gson.springboot.model.pojos.ExamineItem;
import cn.gson.springboot.model.pojos.ExamineRecord;
import cn.gson.springboot.model.pojos.Exchange;
import cn.gson.springboot.model.pojos.Hospital;
import cn.gson.springboot.model.pojos.Invoice;
import cn.gson.springboot.model.pojos.InvoiceDetail;
import cn.gson.springboot.model.pojos.Leave;
import cn.gson.springboot.model.pojos.MedicalCardPx;
import cn.gson.springboot.model.pojos.Operation;
import cn.gson.springboot.model.pojos.OperationRecord;
import cn.gson.springboot.model.pojos.Theater;
import cn.gson.springboot.model.pojos.User;
import cn.gson.springboot.model.vo.AdviceVO;
import cn.gson.springboot.model.vo.ExamineVO;
import cn.gson.springboot.model.vo.InvoiceVO;

@Service//住院模块
@Transactional(rollbackFor=Exception.class)
public class HospitalService {

	@Autowired
	private MedicalCardDAO mdao;//医疗卡dao
	@Autowired
	private MedicalMapper mm;//医疗卡mapper
	@Autowired
	private HospitalDAO hdao;//住院登记dao
	@Autowired
	private HospitalMapper hm;//住院登记mapper
	@Autowired
	private DepartmentsDAO ddao;//科室dao
	@Autowired
	private DepartmentsMapper dm;//科室mapper
	@Autowired
	private BedMapper bedm;//床位mapper
	@Autowired
	private BedDAO beddao;//床位dao
	@Autowired
	private UserMapper userm;//用户mapper
	@Autowired
	private UserDAO userdao;//用户dao
	@Autowired
	private CashDAO cashdao;//押金dao
	@Autowired
	private CashMapper cash_m;//押金mapper
	@Autowired
	private ExchangeDAO exdao;//调整记录dao
	@Autowired
	private AdviceMapper am;//医嘱mapper
	@Autowired
	private AdviceDAO adao;//医嘱dao
	@Autowired
	private DrugsYkMapper drugm;//药品mapper
	@Autowired
	private AdviceDetailsDAO adetailsdao;//医嘱详情dao
	@Autowired
	private AdviceMapper adm;//医嘱详情mapper
	@Autowired
	private InvoiceDAO idao;//用药申请dao
	@Autowired
	private InvoiceDetailsDAO idedao;//用药申请详情dao
	@Autowired
	private ClearingDetailsDAO clearDetaildao;//结算详情dao
	@Autowired
	private ClearingDAO cleardao;//结算dao
	@Autowired
	private ClearingMapper clearm;//结算mapper
	@Autowired
	private LeaveDAO leavedao;//出院dao
	@Autowired
	private OperationMapper opm;//手术mapper
	@Autowired
	private OperationDAO opdao;//手术mapper
	@Autowired
	private ExamineDAO examdao;//体检登记dao
	@Autowired
	private ExamineMapper exam;//体检mapper
	@Autowired
	private ExamineItemDAO ed;
	@Autowired
	private ComboDAO codao;//套餐dao
	@Autowired
	private ExamineRecordDAO erdao;//体检记录dao
	@Autowired
	private CaseDAO casedao;//病历dao
	@Autowired
	private RepertoryMapper rem;//科室库存mapper
	@Autowired
	private HospitalnoticeDAO hndao;//住院通知dao
	@Autowired
	private TheaterDAO tdao;//手术室dao
	@Autowired
	private OperationMapper operationMapper;//手术室mapper
	@Autowired
	private OperationRecordDAO orDAO;//手术记录dao
	
	//科室库存
	public JSONArray findDeptDrug(Integer did,String dname) {
		if(dname != null) {
			if("".equals(dname.trim())) {
				dname = null;
			}
		}
		return rem.findDeptDrug(did,dname);
	}
	
	//病历增删改
	public void addCase(Case c) {
		JSONArray array = findPatientDate(c.getHospital().getHospitalId());
		System.out.println(array+"---"+array.size());
		JSONObject obj = array.getJSONObject(0);
		if(obj!=null&&obj.containsKey("case_id")) {
			c.setCaseId((Integer)array.getJSONObject(0).get("case_id"));
		}
		
		Hospital hospital = hdao.findById(c.getHospital().getHospitalId()).get();
		hospital.setHospitalState("住院中");
		c.setHospital(hospital);
		casedao.save(c);
	}
	
	//体检人身份信息
	public JSONArray findByEidP(Integer eid) {
		return exam.findByEidP(eid);
	}
	
	//已经体检完的人
	public JSONArray findExOk(Integer eid) {
		return exam.findExOk(eid);
	}
	
	//体检号查询项目
	public void addExR(JSONArray array,User user) {
		for (int i = 0; i < array.size(); i++) {
			Integer eid =  (Integer) array.getJSONObject(i).get("examine_record_id");
			String rsult = "" + array.getJSONObject(i).get("examine_record_result");
			ExamineRecord er = erdao.findById(eid).get();
			er.setExamineRecordId(eid);
			er.setExamineRecordResult(rsult);
			er.setExamineRecordName(user.getUserName());
			er.setExamineRecordTime(new Timestamp(new Date().getTime()));
			if("".equals(rsult.trim())) {
				er.setExamineRecordResult(null);
			}
			erdao.save(er);
		}
	}
	
	//体检号查询项目
	public JSONArray findByEid(Integer eid) {
		return exam.findByEid(eid);
	}
	
	//新增床位
	public void addBed(String number,User user) {
		Bed bed = new Bed();
		bed.setBedNumber(number);
		bed.setDepartmentsPx(user.getDepartmentsPx());
		beddao.save(bed);
	}
	
	//已收费的体检项目
	public JSONArray findExByState(Integer eid) {
		return exam.findExRe(eid);
	}
	
	//新增体检
	public void addExamineR(ExamineVO xo,Integer i) {
		//新增个人信息
		MedicalCardPx card = mdao.save(xo.getMc());
		//新增体检登记
		Examine ex = new Examine();
		ex.setMedicalCardPx(card);
		ex.setExamineTime(new Timestamp(new Date().getTime()));
		ex.setExamineState("0");
		if(i==1) {
			ex.setExamineState("1");		
		}
		examdao.save(ex);
		Combo combo = xo.getCombo(); 
		//新增体检记录
		for (ExamineItem item : xo.getItems()) {
			ExamineRecord er = new ExamineRecord();
			er.setExamineItem(item);
			er.setExamine(ex);
			er.setCombo(combo);
			System.out.println("体检项目："+item.getExamineItemId());
			erdao.save(er);
		}
	}

	//查询套餐详情
	public JSONArray findComboDetails(Integer cid) {
		
		return exam.findComboDetails(cid);
	}
	
	//查询套餐
	public JSONArray findCombe() {
		
		return exam.findCombo();
	}
	
	//查询体检项目
	public JSONArray findExamine(String ex) {
		if(ex!=null) {
			return exam.findexamin("%"+ex+"%");
		}
		return exam.findexamin(null);
	}
	
	//所有手术安排记录
	public JSONArray findAllOps() {
		return opm.findAllOps();
	}
	
	//手术结果
	public void updateResult(Integer rid,String result,User user) {
		OperationRecord record = orDAO.findById(rid).get();
		record.setOperationRecordState(result);//手术结果
		Hospital hospital = hdao.findById(record.getHospital().getHospitalId()).get();
		Operation operation = opdao.findById(record.getOperation().getOperationId()).get();
		//结算详单
		ClearingDetail clear_detail = new ClearingDetail();
		clear_detail.setClearingName(user.getUserName());
		//日结详情数量
		clear_detail.setClearing_details_number(1);
		//日结详情单价
		clear_detail.setClearing_details_price(operation.getOpertationMoney());
		//日结详情费用项名称
		clear_detail.setClearingItem(operation.getOperationName());
		//日结详情单位
		clear_detail.setClearingUnit("次");
		//日结详情费用项类型
		clear_detail.setClearingType("手术");
		//日结详情记账时间
		clear_detail.setTallyTime(new Timestamp(new Date().getTime()));
		//住院号和当前日期查询今日结算总单
		JSONArray array = clearm.findClearByDate(hospital.getHospitalId());
		//结算总单
		Clearing clearing = new Clearing();
		System.out.println("执行人---"+user.getUserName());
		System.out.println("结算----"+array);
		if(array!=null && array.size()>0) {
			Integer cid = (Integer) array.getJSONObject(0).get("clearing_id");
			clearing =  cleardao.findById(cid).get();
			//得到本次金额
			BigDecimal price = operation.getOpertationMoney();
			System.out.println("总价格--"+price+"--"+clearing.getClearingMoney());
			//再总金额累加
			BigDecimal totalMoney = clearing.getClearingMoney().add(price);
			clearing.setClearingMoney(totalMoney);
			//总数量累加
			Integer totalNumber = clearing.getClearingNumber()+1;
			//数量累加
			clearing.setClearingNumber(totalNumber);
		}else {
			//如果没有记录则新增今日的结算总单
			clearing.setClearingNumber(clear_detail.getClearing_details_number());
			clearing.setClearingMoney(clear_detail.getClearing_details_price());
			clearing.setClearingTime(new java.sql.Date(System.currentTimeMillis()));
			clearing.setHospital(hospital);
			cleardao.save(clearing);
		}
		clear_detail.setClearing(clearing);
		clearDetaildao.save(clear_detail);
	}

	//删除手术
	public void deleteOps(Integer rid) {
		OperationRecord record = orDAO.findById(rid).get();
		orDAO.delete(record);
	}
	
	//新增手术安排
	public boolean addOps(OperationRecord op,User user) {
		String start_time = op.getOperation_start_time()+"";
		String end_time = op.getOperation_end_time()+"";
		String st = start_time.substring(0, 10);
		String et = st+" "+end_time;
		JSONArray s = opm.findByDate(start_time,et,op.getTheater().getTheaterId());
		System.out.println("数组--"+s +"--"+ s.getJSONObject(0).get("s"));
		System.out.println("开始时间="+start_time);
		System.out.println("--结束时间："+et);
		if(s.getJSONObject(0).getInteger("s") > 0 ) {
			return false;
		}
		//手术新增
		op.setUser1(user);
		orDAO.save(op);
		return true;
	}
	
	//查询该科室下的手术项目
	public JSONArray findOps() { 
		return opm.findOps();
	};
	
	//查询手术室
	public JSONArray findAllTheater() { 
		return operationMapper.findAllTheater();
	};
	
	//查询出院记录
	public JSONArray findLeave(String hid) {
		if(hid != null) {
			if("".equals(hid.trim())) {
				hid = null;
			}
		}
		return hm.findLeave(hid);
	}
	
	//结算明细
	public JSONArray clearDetails(Integer hid,Integer type) {
		JSONArray array = clearm.clearDetails(hid, type);
		System.out.println("明细 =="+array);
		return array; 
	}
	
	//出院登记并未结算的人 
	public JSONArray findLeave() {
		return hm.findLeave2();
	}
	
	//新增出院记录
	public void addLeave(Leave leave,User user) {
		leave.setLeaveTime(new Timestamp(new Date().getTime()));
		leave.setLeaveName(user.getUserName());
		Hospital hospital = hdao.findById(leave.getHospital().getHospitalId()).get();
		hospital.setHospitalState("已出院");
		leavedao.save(leave);
	}
	
	//费用查询
	public JSONArray findCost(Integer hid,Integer opin) {
		return clearm.findCost(hid,opin);
	}
	
	//执行医嘱
	public boolean exAdvice(Integer aid,User user) {
		//医嘱详单
		AdviceDetail ad = adetailsdao.findById(aid).get();
		//科室id;
		Integer did =user.getDepartmentsPx().getDepartmentsId();
		//查询科室库存
		JSONArray deptDrug = findDeptDrug(did , null);
		System.out.println("---科室库存"+deptDrug);
		for (int i = 0; i < deptDrug.size(); i++) {	
			Integer drugId = (Integer) deptDrug.getJSONObject(i).getInteger("drug_id");
			if(drugId == ad.getDrugsYk().getDrugId()) {
				Integer amount = deptDrug.getJSONObject(i).getInteger("amount");
				if(amount<=0) {
					System.out.println("---库存0进这里--");
					return false;
				}
				System.out.println("---库存数量--"+amount);
			}
		}
		ad.setExecuteTime(new Timestamp(new Date().getTime()));
		ad.setExecuteName(user.getUserName());
		if(ad.getAdvice().getAdviceDays()==1) {
			ad.setExecuteState("1");
		}
		//科室减库存
		rem.updateAmount(did, ad.getDrugsYk().getDrugId(), 1);
		adetailsdao.save(ad);
		clearing(ad, user);
		return true;
	}
	
	//请领详情
	public JSONArray findInvoiceDetails(Integer inid) {
		return rem.findInvoiceDetails(inid);
	}
	
	//请领记录
	public JSONArray findInvoice(String dname) {
		return rem.findInvoice(dname);
	}
	
	//药品请领
	public void addInvoice(InvoiceVO iv) {
		//新增请领
		iv.getInvoice().setInvoiceTime(new Timestamp(new Date().getTime()));
		Invoice in = idao.save(iv.getInvoice());
		//新增请领详情
		for (InvoiceDetail ind : iv.getDetails()) {
			ind.setInvoice(in);
			idedao.save(ind);
		}
	}
	
	//停嘱
	public void updateAdvice(Integer aid ) {
		Advice advice = adao.findById(aid).get();
		advice.setAdviceDays(0);
		advice.setAdviceState("已停嘱");
	}
	
	//医嘱id查详情
	public JSONArray findAdDetail(Integer aid ) {
		 
		return adm.findAdDetail(aid);
	}
	
	//所有医嘱
	public JSONArray findAdvice(Integer did,String str) {
		if(str != null) {
			if("".equals(str.trim())) {
				str = null;
			}
		}
		return adm.findAdvice(did,str);
	}
	
	//医嘱执行记录
	public JSONArray findAdviceRecord(Integer hid) {
		return adm.findAdviceRecord(hid);
	}
	
	//医嘱详情
	public JSONArray findAdviceDetails(Integer hid) {
		return adm.findAdviceDetails(hid);
	}
	
	//医嘱新增
	public void addAdvice(AdviceVO av,User user) {
		av.getAdvice().setAdviceDoctor(user.getUserName());
		av.getAdvice().setAdviceTime(new Timestamp(new Date().getTime()));
		av.getAdvice().setAdviceState("待执行");
		adao.save(av.getAdvice());
		List<ExamineItem> items = new ArrayList<>();
		int i = 0;
		Clearing clearing = new Clearing();
		for (AdviceDetail details : av.getDetails()) {
			String type = details.getExecuteType();
			System.out.println("医嘱类型--"+type);
			details.setExecuteState("0");
			details.setAdvice(av.getAdvice());
			if("药品".equals(type)) {//医嘱详情新增
				adetailsdao.save(details);
			}
			if("检查".equals(type)) {
				ExamineItem item = new ExamineItem();
				item.setExamineItemId(details.getDrugsYk().getDrugId());
				items.add(item);
				ExamineItem examineItem = ed.findById(details.getDrugsYk().getDrugId()).get();
				details.getDrugsYk().setDrugSellingPrice(examineItem.getExamineItemPrice());
				details.getDrugsYk().setDrugName(examineItem.getExamineItemName());
				details.getDrugsYk().setDrugNumber(1);
				details.getDrugsYk().setDrugSpecifications("次");
				//结算详单
				ClearingDetail clear_detail = new ClearingDetail();
				clear_detail.setClearingName(user.getUserName());
				//日结详情数量
				clear_detail.setClearing_details_number(details.getAdvice_Details_number());
				//日结详情单价
				clear_detail.setClearing_details_price(details.getDrugsYk().getDrugSellingPrice());
				//日结详情费用项名称
				clear_detail.setClearingItem(details.getDrugsYk().getDrugName());
				//日结详情单位
				clear_detail.setClearingUnit(details.getDrugsYk().getDrugSpecifications());
				//日结详情费用项类型
				clear_detail.setClearingType(details.getExecuteType());
				//日结详情记账时间
				clear_detail.setTallyTime(details.getExecuteTime());
				//住院号和当前日期查询今日结算总单
				JSONArray array = clearm.findClearByDate(details.getAdvice().getHospital().getHospitalId());
				//结算总单
				System.out.println("执行人---"+user.getUserName());
				System.out.println("结算----"+array);
				if(array!=null && array.size()>0) {
					Integer cid = (Integer) array.getJSONObject(0).get("clearing_id");
					clearing =  cleardao.findById(cid).get();
					//得到本次金额
					BigDecimal price = details.getDrugsYk().getDrugSellingPrice().multiply(new BigDecimal(details.getAdvice_Details_number()));
					System.out.println("总价格--"+price+"--"+clearing.getClearingMoney());
					//再总金额累加
					BigDecimal totalMoney = clearing.getClearingMoney().add(price);
					clearing.setClearingMoney(totalMoney);
					System.out.println(clearing.getClearingNumber()+"数量——"+details.getAdvice_Details_number());
					//总数量累加
					Integer totalNumber = clearing.getClearingNumber()+details.getAdvice_Details_number();
					//数量累加
					clearing.setClearingNumber(totalNumber);
				}else {
					//如果没有记录则新增今日的结算总单
					clearing.setClearingNumber(clear_detail.getClearing_details_number());
					clearing.setClearingMoney(clear_detail.getClearing_details_price());
					clearing.setClearingTime(new java.sql.Date(System.currentTimeMillis()));
					clearing.setHospital(details.getAdvice().getHospital());
					if(i == 0) {
						clearing = cleardao.save(clearing);
						i++;
					}
				}
				clear_detail.setClearing(clearing);
				clearDetaildao.save(clear_detail);
			}
		}
		//体检新增
		ExamineVO ev = new ExamineVO();
		Integer hid = av.getAdvice().getHospital().getHospitalId();
		Hospital hospital = hdao.findById(hid).get();
		ev.setMc(hospital.getMedicalCardPx());
		ev.setItems(items);
		addExamineR(ev,1);
	}
	
	public void clearing(AdviceDetail ad,User user) {
		//结算详单
		ClearingDetail clear_detail = new ClearingDetail();
		clear_detail.setClearingName(user.getUserName());
		//日结详情数量
		clear_detail.setClearing_details_number(ad.getAdvice_Details_number());
		//日结详情单价
		clear_detail.setClearing_details_price(ad.getDrugsYk().getDrugSellingPrice());
		//日结详情费用项名称
		clear_detail.setClearingItem(ad.getDrugsYk().getDrugName());
		//日结详情单位
		clear_detail.setClearingUnit(ad.getDrugsYk().getDrugSpecifications());
		//日结详情费用项类型
		clear_detail.setClearingType(ad.getExecuteType());
		//日结详情记账时间
		clear_detail.setTallyTime(ad.getExecuteTime());
		//住院号和当前日期查询今日结算总单
		JSONArray array = clearm.findClearByDate(ad.getAdvice().getHospital().getHospitalId());
		//结算总单
		Clearing clearing = new Clearing();
		System.out.println("执行人---"+user.getUserName());
		System.out.println("结算----"+array);
		if(array!=null && array.size()>0) {
			Integer cid = (Integer) array.getJSONObject(0).get("clearing_id");
			clearing =  cleardao.findById(cid).get();
			//得到本次金额
			BigDecimal price = ad.getDrugsYk().getDrugSellingPrice().multiply(new BigDecimal(ad.getAdvice_Details_number()));
			System.out.println("总价格--"+price+"--"+clearing.getClearingMoney());
			//再总金额累加
			BigDecimal totalMoney = clearing.getClearingMoney().add(price);
			clearing.setClearingMoney(totalMoney);
			System.out.println(clearing.getClearingNumber()+"数量——"+ad.getAdvice_Details_number());
			//总数量累加
			Integer totalNumber = clearing.getClearingNumber()+ad.getAdvice_Details_number();
			//数量累加
			clearing.setClearingNumber(totalNumber);
		}else {
			//如果没有记录则新增今日的结算总单
			clearing.setClearingNumber(clear_detail.getClearing_details_number());
			clearing.setClearingMoney(clear_detail.getClearing_details_price());
			clearing.setClearingTime(new java.sql.Date(System.currentTimeMillis()));
			clearing.setHospital(ad.getAdvice().getHospital());
			cleardao.save(clearing);
		}
		clear_detail.setClearing(clearing);
		clearDetaildao.save(clear_detail);
	}
	
	//药品查询
	public JSONArray findDrug(Integer tid,String name) {
		return drugm.findDrug_ljw(tid,name);
	}
	
	//患者信息
	public JSONArray findPatientDate(Integer hid) {
		return hm.findPatientDate(hid);
	}
	
	//患者查询
	public JSONArray findPatient(Integer did) {
		return am.findPatient(did);
	}
	
	//被手术者信息
	public JSONArray findLeavePatient(String hid,Integer did) {
		if(hid!=null) {
			if("".equals(hid.trim())) {
				hid = null;
			}
		}
		return hm.findLeavePatient(hid,did);
	}
	
	//调整记录
	public JSONArray findExchange(String hid) {
		if(hid!=null) {
			if("".equals(hid.trim())) {
				hid = null;
			}
		}
		return bedm.findExchange(hid);
	}
	
	//床位调整
	public void exchange_bed(Exchange ex,Bed old,Bed now,Hospital hos) {
		//新增调增记录
		ex.setHospital(hos);
		ex.setExchangeAgo(old.getBedNumber());
		ex.setExchangeNow(now.getBedNumber());
		ex.setExchangeTime(new Timestamp(new Date().getTime()));
		ex.setExchangeName("秀芹");
		exdao.save(ex);
		System.out.println("--原床位--"+old.getBedNumber());
		System.out.println("--新床位--"+now.getBedNumber());
		//修改床位
		old.setHospital(null);
		now.setHospital(hos);
		beddao.save(old);
		beddao.save(now);
	}
	
	//新增押金记录
	public void addCash(Cash cash,Integer i,String name) {
		Hospital hospital = findHospitalByid(cash.getHospital().getHospitalId());
		if(i==1) {
			cash.setCashType("预交");
		}else {
			cash.setCashType("退费");
			cash.setCashMethod("现金");
		}
		cash.setCashName(name);
		cash.setHospital(hospital);
		cashdao.save(cash);
	}
	
	//押金记录
	public JSONArray findCashRecord(String hid) {
		if(hid!=null) {
			if("".equals(hid.trim())) {
				hid = null;
			}
		}
		return cash_m.findCashRecord(hid);
	}
	
	//催缴单
	public JSONArray findPayment(Integer hid) {
		return cash_m.findPayment(hid);
	}
	
	//押金统计查询
	public JSONArray findCashTotal(String hid) {
		return cash_m.findCashTotal(hid);
	}
	
	//新增住院登记
	public boolean register(MedicalCardPx card,Cash cash,Integer did,
			Integer bed_id,Hospital hos , User user) {
		System.out.println("---card--"+card.getMzcardId());
		System.out.println("医生id--"+hos.getUser1().getUserId());
		Integer i = hm.findByMid(card.getMzcardId());
		System.out.println("住院中--"+i);
		if(i>0) {
			return false;
		}
		if(card.getMzcardId()==0) {
			mdao.save(card);
		}
		//医生对象
		User doctor = findUserByid(hos.getUser1().getUserId());
		//护士对象
		//User nurse = findUserByid(hos.getUser2().getUserId());
		//科室对象
		DepartmentsPx departments = findDepartmentsByid(did);
		//床位对象
		Bed bed = findBedByid(bed_id);
		//新增住院
		hos.setMedicalCardPx(card);
		hos.setUser1(doctor);
		//hos.setUser2(nurse);
		hos.setDepartmentsPx(departments);
		hos.setHospitalName(user.getUserName());
		hos.setHospitalState("待看诊");
		hos.setHospitalTime(new Timestamp(new Date().getTime()));
		hos.setHospitalCash(cash.getCashMoney());
		hdao.save(hos);
		//床位修改
		bed.setHospital(hos);
		beddao.save(bed);
		//新增押金记录
		cash.setCashTime(new Timestamp(new Date().getTime()));
		cash.setCashType("预交");
		cash.setHospital(hos);
		cash.setCashName(user.getUserName());
		cashdao.save(cash);
		return true;
	}  
	
	//查询所有住院登记记录
	public JSONArray findHospital(String hid) {
		if(hid!=null) {
			if("".equals(hid.trim())) {
				hid = null;
			}
		}
		return hm.findHospital(hid);
	}
	
	//id查询住院单表
	public Hospital findHospitalByid(Integer hid) {
		return hdao.findById(hid).get();
	}
	
	//住院通知查询
	public MedicalCardPx findMedByid(String hnid) {
		JSONArray array = hm.findByHnId(hnid);
		MedicalCardPx px = new MedicalCardPx();
		if(array.size()>0&&array!=null) {
			px.setMzcardId((int) array.getJSONObject(0).get("mzcard_id"));
			px.setPatientAge((int) array.getJSONObject(0).get("patient_age"));
			px.setPatientName((String) array.getJSONObject(0).get("patient_name"));
			px.setPatientSex((String) array.getJSONObject(0).get("patient_sex"));
			px.setHomeAddress((String) array.getJSONObject(0).get("home_address"));
			px.setCardCid((String) array.getJSONObject(0).get("card_cid"));
			px.setMzcardPhone((String) array.getJSONObject(0).get("mzcard_phone"));
			px.setDid((int) array.getJSONObject(0).get("departments_id"));
			return px;
		}
		return null;
	}
	
	//id查询科室
	public DepartmentsPx findDepartmentsByid(Integer did) {
		return  ddao.findById(did).get();
	} 
	
	//所有科室查询
	public JSONArray findDepartments() {
		return  dm.findDepartments();
	} 
	//所有科室查询
	public JSONArray cxsyks() {
			return  dm.cxsyks();
	}
	
	//查询该科室下的角色
	public JSONArray findRoleAndDept(Integer did,Integer rid) {
		return  dm.findRoleAndDept(did,rid);
	}
	
	//查询该科室下的空床位
	public JSONArray findBedByDept(Integer did){
		return dm.findBedByDept(did);
	}
	
	//id查询床位
	public Bed findBedByid(Integer bid) {
		return beddao.findById(bid).get();
	}
	
	//查询床位
	public JSONArray findBed(String hid,Integer did) {
		if(hid != null) {
			if("".equals(hid.trim())) {
				hid = null;
			}
		}
		return bedm.findBed(hid,did);
	}
	
	//id查询user
	public User findUserByid(Integer uid) {
		return userdao.findById(uid).get();
	}
	
	//床位的增删改
	public Bed addBed(Bed bed) {
		return beddao.save(bed);
	}
}
